// 显示学生照片

zz.Office.PhotoviewPanel = function(config) {
	zz.Office.PhotoviewPanel.superclass.constructor.call(this, config);

	var proxy = new Ext.data.HttpProxy({
				url : 'getstudentlist.do?tab=personinfo'
			});
	var recordType = new Ext.data.Record.create([{
				name : "id",
				type : "string"
			}, {
				name : "birthday",
				dateFormat : 'Y-m-d',
				type : "date"
			}, {
				name : "sex",
				type : "string"
			}, {
				name : "ename",
				type : "string"
			}, {
				name : "pass_id",
				type : "string"
			}, {
				name : "memo",
				type : "string"
			}, {
				name : "hasphoto",
				type : "string"
			}, {
				name : "sid",
				type : "string"
			}, {
				name : "iclass",
				type : "string"
			}, {
				name : "study",
				type : "string"
			}, {
				name : "cname",
				type : "string"
			}, {
				name : "kname",
				type : "string"
			}, {
				name : "subname",
				type : "string"
			}, {
				name : "result",
				type : "string"
			}, {
				name : "course",
				type : "string"
			}, {
				name : "pb_id",
				type : "string"
			}]);

	// 定义分析器
	var reader = new Ext.data.JsonReader({
				totalProperty : "results",
				root : "rows",
				id : "id"
			}, recordType);

	// 定义store
	var ds = new Ext.data.Store({
				id : 'dss_pi',
				proxy : proxy,
				reader : reader
			});
	this.ds = ds;
	/*ds.on('load', function() {
				var d = Ext.getCmp('cosmenu_phow');
				if (d.getText() != '全部') {
					ds.filter('course', d.getText());
				}
				putClassEl();
			});*/

	var mytoolbar = new Ext.Toolbar([
			'',
			{
				id : 'cosmenu_phow',
				text : '全部',
				iconCls : 'im16x16',
				handler : function() {
					// putClassEl();
					if (!(this.text == '全部'))
						putClassEl();
					ds.clearFilter();
					fliterOptation(this.text, '全部班级');
				},
				xtype : 'splitbutton',
				menu : new Ext.menu.Menu({
							items : [{
								text : '全部',
								iconCls : 'im16x16',
								handler : function() {
									putClassEl();
									// ds.filter("course", this.text)
									fliterOptation(this.text, Ext
													.getCmp('classel_phow').text);
									Ext.getCmp('cosmenu_phow')
											.setText(this.text);
								}
							}, {
								text : '基本课程',
								iconCls : 'user-kid',
								handler : function() {
									putClassEl();
									// ds.filter("course", this.text)
									fliterOptation(this.text, Ext
													.getCmp('classel_phow').text);
									Ext.getCmp('cosmenu_phow')
											.setText(this.text);
								}
							}, {
								text : '深化课程',
								iconCls : 'user-suit',
								handler : function() {
									putClassEl();
									// ds.filter("course", this.text)
									fliterOptation(this.text, Ext
													.getCmp('classel_phow').text);
									Ext.getCmp('cosmenu_phow')
											.setText(this.text);

								}
							}, {
								text : '双学位课程',
								iconCls : 'user-girl',
								handler : function() {
									putClassEl();
									// ds.filter("course", this.text)
									fliterOptation(this.text, Ext
													.getCmp('classel_phow').text);
									Ext.getCmp('cosmenu_phow')
											.setText(this.text);

								}
							}]
						})

			},
			'',
			'-',
			'',
			{
				id : 'classel_phow',
				text : '全部班级',
				iconCls : 'im16x16',
				handler : function() {
					var fls = this.text;
					fliterOptation(Ext.getCmp('cosmenu_phow').text, this.text);
				},
				xtype : 'splitbutton',
				menu : new Ext.menu.Menu({
							items : null
						}),
				listeners : {}
			},
			'',
			'-',
			'',
			'<img src=pic/s.gif style="background:url(images/find_user_icon.gif); width:16px" />',
			{
				width : 80,
				id : 'sidquery_phow',
				xtype : 'numberfield',
				emptyText : '输入学号...',
				// enableKeyEvents : true,
				listeners : {
					'blur' : function(el) {
						el.setValue('');
					},
					'render' : function(el1) {
						// el1.setValue('');
						Ext.get('sidquery_phow').on('keypress', function(e, el) {
							var querystr = 'sid';
							var k = e.getKey();

							if (k == 13) {
								ds.clearFilter()
								ds.filterBy(function(record) {
									var b = Ext.getCmp('cosmenu_phow').text
											.indexOf('全部') >= 0
											? true
											: Ext.getCmp('cosmenu_phow').text == record
													.get('course');
									b &= Ext.getCmp('classel_phow').text
											.indexOf('全部') >= 0
											? true
											: Ext.getCmp('classel_phow').text == record
													.get('iclass');
									return b
											&& record.get(querystr)
													.indexOf(el.value) > -1
								});
							}
						});

					}
				}
			}/*, '->', {
				id : 'saveconfirm_phow',
				text : '编辑选项',
				width : 80,
				handler : null,
				xtype : 'splitbutton',
				menu : new Ext.menu.Menu({
					items : [{
								text : '修改前需确认',
								handler : function() {
									grid.on("afteredit", function(e) {
												saveBtnHandler(null, e)
												return false; // 阻止事件继续传播
											}, grid);
									Ext.getCmp('saveconfirm_phow')
											.setText(this.text);
									Ext.getCmp('saveconfirm_phow').handler = null;
								}
							}, {
								text : '不提示直接修改',
								handler : function() {
									grid.on("afteredit", function(e) {
												saveBtnHandler(null, e)
												return false;
											}, grid);
									Ext.getCmp('saveconfirm_phow')
											.setText(this.text);
									Ext.getCmp('saveconfirm_phow').handler = null;
								}
							}, {
								text : '修改后统一提交',
								handler : function() {
									grid.un("afteredit", function(e) {
												saveBtnHandler(null, e)
												return false;
											}, grid); // 取消grid编辑后的提交动作
									Ext.getCmp('saveconfirm_phow')
											.setText(this.text);
									Ext.getCmp('saveconfirm_phow').handler = saveBtnHandler;
								}
							}]
				})
				// arrowHandler: function(){Ext.MessageBox.alert("","ooo")}
			}*/]);
	// mytoolbar end

    var tpl = new Ext.XTemplate(
		'<tpl for=".">',
            '<div class="thumb-wrap" id="{id}">',
		    '<div class="thumb"><img src= "'+photopath + '/photo/{sid}.jpg" title="{shortName}" ></img></div>',
		    '<span class="x-editable">{shortName}</span></div>',
        '</tpl>',
        '<div class="x-clear"></div>'
	);	
var photoview = new Ext.Panel({
        id:'images-view',
        frame:true,
        region : "center",
       // autoHeight:true,
        tbar : mytoolbar,
        autoScroll:true,
        layout:'fit',
        //title:'Simple DataView (0 items selected)',

        items: new Ext.DataView({
            store: ds,
            tpl: tpl,
           // autoHeight:true,
        autoScroll:true,
            multiSelect: true,
            overClass:'x-view-over',
            itemSelector:'div.thumb-wrap',
            emptyText: 'No images to display',

            prepareData: function(data){
                //data.shortName = Ext.util.Format.ellipsis(data.ename, 15);
                data.shortName = data.sid+'-'+(data.cname!='' ? data.cname : '')+'-'+(data.kname!='' ? data.kname : '');
                //data.dateString = data.lastmod.format("m/d/Y g:i a");
                return data;
            },
            
            listeners: {
            	/*selectionchange: {
            		fn: function(dv,nodes){
            			var n = nodes[0]
            			if(n.id){
	            			var re = ds.getById(n.id);	 
            				setDetailsPanel(re);
            			}
            		}
            	}*/
            	click: {
            		fn: function(dv,i,n){
            			//var n = nodes[0]
            			if(n && n.id){
	            			var re = ds.getById(n.id);	 
            				setDetailsPanel(re);
            			}
            		}
            	}
            }
        })
    });

	function remoteQuery(cosname, classname, subjectstr) {
		// 查询远程数据，要求返回相关全部数据，即在subject上选课与未选课的人
		// ,即若无人选课，应能得到全部人名单
		ds.load({
					params : {
						subname : subjectstr
					}
				});
	}

	function fliterOptation(cosname, classname, subjectstr) {
		// 使用fliteby的处理函数，处理班级课程间过滤联动关系,
		// 因为是单科成绩表，所以联动需加入subcombo的值
		ds.clearFilter();
		ds.filterBy(function(re) {
					var b = true;
					// 不能显示没有选课的人，考虑吧课程查询作为触发远程查询
					if (cosname.indexOf('全部') >= 0) { // 
						return b;
					} else if (classname.indexOf('全部') >= 0) { // 筛选class时，要考虑course的筛选继续有效
						b &= re.get('course') == cosname;
					} else {
						b &= re.get('course') == cosname;
						b &= re.get('iclass') == classname;
					}
					if (!(Ext.isEmpty(subjectstr)))
						b &= re.get('subname') == subjectstr
								|| Ext.isEmpty(re.get('subname'));
					return b;
				});
	}

	function putClassEl() {
		// 从grid store中提取班级
		Ext.getCmp('classel_phow').menu.removeAll();
		Ext.getCmp('classel_phow').menu.add({
					text : '全部班级',
					iconCls : 'im16x16',
					handler : function() {
						var s = this.text;
						fliterOptation(Ext.getCmp('cosmenu_phow').text, this.text);
						Ext.getCmp('classel_phow').setText(this.text);
					}
				});
		Ext.getCmp('classel_phow').setText('全部班级');
		var sz = '|';
		ds.data.each(function(re) {
					if (re.get('course') != Ext.getCmp('cosmenu_phow').getText())
						return;
					var c = re.get('iclass');
					if (c && c != '' && c != '-') {
						if (sz.indexOf('|' + c + '|') < 0) { // sz like
							// '|1-2|2-1|3-5|'
							sz += c + '|';
							var newclass = new Ext.menu.Item({
										text : c,
										iconCls : 'user-girl',
										handler : function() {
											fliterOptation(
													Ext.getCmp('cosmenu_phow').text,
													this.text);
											Ext.getCmp('classel_phow').setText(c);
										}
									});
							var m = Ext.getCmp('classel_phow').menu;
							// debugger
							m.add(newclass);
						}

					}
				});
		// 班级结束
	}

	/**
	 * 先修改，一次性提交 btn-提交按钮控件 e-当逐条提交修改时的编辑事件，含当前record等 ***********************
	 */
	function saveBtnHandler(btn, e) {
		var a = Ext.getCmp('saveconfirm_phow');
		if (a.text != '不提示直接修改' && a.text != '修改前需确认' && a.text != '修改后统一提交')
			return;
		else if (a.text == '修改后统一提交' && !btn) // 当为'修改后统一提交'时不响应afertrowedit事件
			return;

		var storeObj = ds;
		var modifiedRecords = storeObj.getModifiedRecords();
		var submitRecords = [];

		for (var i = 0, len = modifiedRecords.length; i < len; i++) {
			// 原型语句 submitRecords.push(storeObj.isWithAllFields === true ?
			// modifiedRecords[i].data : modifiedRecords[i].modified); //
			// 获取Record之中的实体数据
			if (modifiedRecords[i].data.sid) {
				submitRecords.push({
							id : modifiedRecords[i].json.id,
							sid : modifiedRecords[i].data.sid,
							course : modifiedRecords[i].data.course,
							/*
							 * subname : modifiedRecords[i].data.subname ?
							 * modifiedRecords[i].data.subname :
							 * Ext.getCmp('subcombo_phow').getValue(),
							 */
							birthday : modifiedRecords[i].data.birthday ? modifiedRecords[i].data.birthday.format('Y-m-d'):'null',
							sex : modifiedRecords[i].data.sex,
							pb_id : modifiedRecords[i].data.pb_id,
							pass_id : modifiedRecords[i].data.pass_id,
							kname : modifiedRecords[i].data.kname,
							cname : modifiedRecords[i].data.cname,
							study : modifiedRecords[i].data.study,
							ename : modifiedRecords[i].data.ename,
							hasphoto : modifiedRecords[i].data.hasphoto,
							memo : modifiedRecords[i].data.memo,
							iclass : modifiedRecords[i].data.iclass
						});
			}
		}
		if (submitRecords.length <= 0)
			return;
		if (a.text != '修改后统一提交') { // 只有当前记录被修改
			if (modifiedRecords.length > 1) {
				if (confirm('有陈旧修改数据，按“确定”清理数据重新输入，或“取消”后修改选项为“统一提交”！'))
					storeObj.commitChanges();
				storeObj.reload();
				return;
			} else {
				if (a.text == '不提示直接修改' || confirm('数据修改将被提交，是否继续？'))
					Ext.Ajax.request({
						url : 'ModifyResult.do?edit=perinfoedit&datecode='
								+ (new Date().getTime()),
						params : {
							submitData : Ext.util.JSON.encode(submitRecords)
						},
						success : function() {
							// alert("保存已成功。");
							storeObj.commitChanges();
						},
						failure : function() {
							alert('你的改变未能正常保存成功!');
						}
							// scope : storeObj
						});
			}

		} else { // 统一提交
			if (submitRecords.length == 0) {
				alert('没有发现修改过的记录，没有内容提交！');
				return;
			}

			// debugger
			btn.disable();
			if (confirm("您确定要进行该操作？") == true) {
				// 正在保存改变，请等待...
				Ext.Ajax.request({
					url : 'ModifyResult.do?edit=perinfoedit&datecode='
							+ (new Date().getTime()),
					params : {
						submitData : Ext.util.JSON.encode(submitRecords)
					},
					success : function() {
						alert("保存已成功。");
						storeObj.commitChanges();
						if (btn)
							btn.enable();
					},
					failure : function() {
						alert('你的改变未能正常保存成功!');
						if (btn)
							btn.enable();
					}
						// scope : storeObj
					});
			} else {
				btn.enable();
			}
		}
	}
	/** 修改结束 *********************** */

	function setDetailsPanel(record) {
		var dgrid = Ext.getCmp('detailsgrid');
		var cmde = new Ext.grid.ColumnModel({
					defaultWidth : 50,
					columns : [{
								header : '类    别',
								align : 'center',
								dataIndex : 'text'
							}, {
								header : '内    容',
								align : 'center',
								dataIndex : 'value'
							}]
				});
		// var outday = "";
		// if(record.json.pb_begin && record.json.pb_out)
		// outday = new Date((new
		// Date(Date.parse(record.json.pb_begin.replace(/-/g,
		// "/")))).getTime()+parseInt(record.json.pb_out)*24*3600*1000);

		var deds = new Ext.data.SimpleStore({
					fields : ['text', 'value'],
					data : [["学号", record.json.sid],
							["中文名", record.json.cname],
							["韩文名", record.json.kname],
							["英文名", record.json.ename],
							["学科", record.json.study],
							["课程", record.json.course],
							["班级", record.json.iclass],
							["护照名", record.json.ename],
							["护照号", record.json.pb_id],
							["签证号", record.json.pb_type],
							["签证起始", record.json.pb_begin],
							["签证终止", record.json.pbtimeout],
							["生日", record.json.birthday],
							["图书证", record.json.memo]]
				});

		dgrid.setTitle(record.json.sid + '-' + (record.json.cname?record.json.cname:'') + '-'
				+ (record.json.kname?record.json.kname:''));
		var imgel = Ext.getDom('stuphoto');
		if (imgel.src)
			imgel.src =  photopath + '/photo/' + record.json.sid
					+ '.jpg'
		dgrid.reconfigure(deds, cmde);
	}

	this.add(photoview);
	// 第三、调整，tbar分页,工具栏
}
Ext.extend(zz.Office.PhotoviewPanel, Ext.Panel, {

});

